package com.yunda.nebula.gateway.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunda.nebula.core.tool.utils.BeanUtil;
import com.yunda.nebula.gateway.core.entity.Result;
import com.yunda.nebula.gateway.core.entity.TbGatewayApp;
import com.yunda.nebula.gateway.entity.dto.AppDTO;
import com.yunda.nebula.gateway.listener.ConfigCreateEvent;
import com.yunda.nebula.gateway.listener.ConfigDeleteEvent;
import com.yunda.nebula.gateway.listener.ConfigUpdateEvent;
import com.yunda.nebula.gateway.service.ITbGatewayAppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * app 前端控制器
 * </p>
 *
 * @author zhiguo.dong
 * @since 2020-09-17
 */
@RestController
@RequestMapping("/nebula/gateway/app")
public class TbGatewayAppController {

    @Autowired
    private ITbGatewayAppService appService;

    @Autowired
    private ApplicationContext context;


    @RequestMapping("/insert.do")
    public Result insert(@RequestBody AppDTO appDTO){
        TbGatewayApp tbGatewayApp = BeanUtil.copy(appDTO, TbGatewayApp.class);
        appService.save(tbGatewayApp);

        context.publishEvent(new ConfigCreateEvent(appDTO.getAppId()));
        return Result.data(null);
    }

    @RequestMapping("/delete.do")
    public Result delete(@RequestParam(value = "appId") String appId){
        appService.remove(new LambdaQueryWrapper<TbGatewayApp>().eq(TbGatewayApp::getAppId,appId));
        context.publishEvent(new ConfigDeleteEvent(appId));

        return Result.data(null);
    }

    @RequestMapping("/update.do")
    public Result update(@RequestBody AppDTO appDTO){
        TbGatewayApp tbGatewayApp = BeanUtil.copy(appDTO, TbGatewayApp.class);
        appService.update(tbGatewayApp,new LambdaQueryWrapper<TbGatewayApp>().eq(TbGatewayApp::getAppId,appDTO.getAppId()));
        context.publishEvent(new ConfigUpdateEvent(appDTO.getAppId()));

        return Result.data(null);
    }

    @RequestMapping("/get.do")
    public Result get(@RequestParam(value = "appId") String appId){
        TbGatewayApp tbGatewayApp = appService.getOne(new LambdaQueryWrapper<TbGatewayApp>().eq(TbGatewayApp::getAppId, appId));

        return Result.data(tbGatewayApp);
    }

    @RequestMapping("/list.do")
    public Result list(@RequestParam(value = "appId" ,required = false) String appId){
        LambdaQueryWrapper<TbGatewayApp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbGatewayApp::getAppId,appId);
        List<TbGatewayApp> list = appService.list(wrapper);
        return Result.data(list);
    }


}

